<template>
  <div class="health-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/pet-center'}">宠物中心</el-breadcrumb-item>
      <el-breadcrumb-item>健康检测</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 健康数据录入 -->
    <el-card class="data-entry">
      <div slot="header">
        <span>健康数据录入</span>
        <el-button
            type="primary"
            icon="el-icon-upload"
            @click="submitData"
            style="float: right;">
          提交记录
        </el-button>
      </div>
      <el-form :model="formData" :rules="rules" ref="healthForm">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="体重 (kg)" prop="weight">
              <el-input-number
                  v-model="formData.weight"
                  :min="0.1"
                  :max="100"
                  :precision="1"
                  controls-position="right">
              </el-input-number>
              <span class="normal-range">正常范围: {{normalRanges.weight}}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="体温 (°C)" prop="temperature">
              <el-input-number
                  v-model="formData.temperature"
                  :min="35"
                  :max="42"
                  :precision="1"
                  controls-position="right">
              </el-input-number>
              <span class="normal-range">正常范围: {{normalRanges.temperature}}</span>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="活动时长 (小时)" prop="activity">
              <el-input-number
                  v-model="formData.activity"
                  :min="0"
                  :max="24"
                  :precision="1">
              </el-input-number>
              <span class="normal-range">推荐范围: {{normalRanges.activity}}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="饮食情况" prop="diet">
              <el-select v-model="formData.diet">
                <el-option label="正常" value="normal"></el-option>
                <el-option label="食欲减退" value="low"></el-option>
                <el-option label="食欲亢进" value="high"></el-option>
                <el-option label="呕吐" value="vomit"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="记录时间" prop="recordTime">
              <el-date-picker
                  v-model="formData.recordTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择记录时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="其他症状" prop="symptoms">
          <el-input
              type="textarea"
              :rows="3"
              v-model="formData.symptoms"
              placeholder="请输入其他异常症状描述">
          </el-input>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 健康数据可视化 -->
    <el-card class="data-visualization">
      <div slot="header">
        <span>健康趋势分析</span>
        <el-select
            v-model="chartType"
            @change="updateChart"
            style="width: 120px; float: right;">
          <el-option label="体重趋势" value="weight"></el-option>
          <el-option label="体温趋势" value="temperature"></el-option>
          <el-option label="活动趋势" value="activity"></el-option>
        </el-select>
      </div>
      <div id="healthChart" style="height: 400px;"></div>
    </el-card>

    <!-- 异常预警面板 -->
    <el-alert
        v-if="hasAbnormal"
        :title="abnormalTitle"
        type="error"
        :description="abnormalDetails"
        show-icon
        class="abnormal-alert">
      <el-button type="text" @click="showAbnormalDetail">查看详情</el-button>
    </el-alert>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'HealthCheck',
  data() {
    // 正常值范围定义
    const normalRanges = {
      weight: '2.5-40kg',
      temperature: '38-39.5°C',
      activity: '2-6小时'
    }

    // 自定义验证规则
    const validateWeight = (rule, value, callback) => {
      if (value < 2.5 || value > 40) {
        callback(new Error(`体重异常！正常范围：${normalRanges.weight}`))
      } else {
        callback()
      }
    }

    const validateTemperature = (rule, value, callback) => {
      if (value < 38 || value > 39.5) {
        callback(new Error(`体温异常！正常范围：${normalRanges.temperature}`))
      } else {
        callback()
      }
    }

    return {
      formData: {
        weight: 15,
        temperature: 38.5,
        activity: 4,
        diet: 'normal',
        recordTime: new Date(),
        symptoms: ''
      },
      normalRanges,
      chart: null,
      chartType: 'weight',
      healthData: [],
      rules: {
        weight: [
          { required: true, message: '请输入体重', trigger: 'blur' },
          { validator: validateWeight, trigger: 'blur' }
        ],
        temperature: [
          { required: true, message: '请输入体温', trigger: 'blur' },
          { validator: validateTemperature, trigger: 'blur' }
        ],
        activity: [
          { required: true, message: '请输入活动时长', trigger: 'blur' }
        ],
        recordTime: [
          { required: true, message: '请选择记录时间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    hasAbnormal() {
      return this.healthData.some(item =>
          item.weight < 2.5 || item.weight > 40 ||
          item.temperature < 38 || item.temperature > 39.5 ||
          item.diet !== 'normal' ||
          item.symptoms
      )
    },
    abnormalTitle() {
      const count = this.healthData.filter(item =>
          item.weight < 2.5 || item.weight > 40 ||
          item.temperature < 38 || item.temperature > 39.5 ||
          item.diet !== 'normal' ||
          item.symptoms
      ).length
      return `检测到 ${count} 条异常记录`
    },
    abnormalDetails() {
      const latest = this.healthData[this.healthData.length - 1]
      const alerts = []
      if (latest) {
        if (latest.weight < 2.5) alerts.push('体重过低')
        if (latest.weight > 40) alerts.push('体重过高')
        if (latest.temperature < 38) alerts.push('体温过低')
        if (latest.temperature > 39.5) alerts.push('体温过高')
        if (latest.diet !== 'normal') alerts.push('饮食异常')
        if (latest.symptoms) alerts.push('其他症状')
      }
      return alerts.join('，')
    }
  },
  mounted() {
    this.initChart()
    this.loadSampleData()
  },
  methods: {
    initChart() {
      this.chart = echarts.init(document.getElementById('healthChart'))
      this.updateChart()
    },
    loadSampleData() {
      // 模拟历史数据
      this.healthData = Array.from({ length: 7 }, (_, i) => ({
        date: `2023-08-${15 + i} 10:00:00`,
        weight: 15 + Math.random() * 2 - 1,
        temperature: 38.5 + Math.random() * 0.5 - 0.25,
        activity: 4 + Math.random() * 2 - 1,
        diet: Math.random() > 0.8 ? 'low' : 'normal',
        symptoms: Math.random() > 0.9 ? '偶尔咳嗽' : ''
      }))
    },
    updateChart() {
      const option = {
        title: { text: `${this.chartType.toUpperCase()} 趋势分析` },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: this.healthData.map(d => d.date.split(' ')[0])
        },
        yAxis: { type: 'value' },
        series: [{
          data: this.healthData.map(d => d[this.chartType]),
          type: 'line',
          smooth: true,
          markArea: {
            itemStyle: {
              color: 'rgba(255, 173, 177, 0.2)'
            },
            data: this.getAlertZone()
          }
        }]
      }
      this.chart.setOption(option)
    },
    getAlertZone() {
      const ranges = {
        weight: [[{ yAxis: 40 }, { yAxis: 100 }], [{ yAxis: 0 }, { yAxis: 2.5 }]],
        temperature: [[{ yAxis: 39.5 }, { yAxis: 42 }], [{ yAxis: 35 }, { yAxis: 38 }]],
        activity: [[{ yAxis: 6 }, { yAxis: 24 }], [{ yAxis: 0 }, { yAxis: 2 }]]
      }
      return ranges[this.chartType]
    },
    submitData() {
      this.$refs.healthForm.validate(valid => {
        if (valid) {
          this.healthData.push({ ...this.formData })
          this.$message.success('数据提交成功')
          this.updateChart()
          this.checkAbnormal()
        }
      })
    },
    checkAbnormal() {
      const latest = this.healthData[this.healthData.length - 1]
      if (latest.temperature > 39.5) {
        this.$notify.error({
          title: '体温过高预警',
          message: `当前体温 ${latest.temperature}°C，建议立即联系兽医！`,
          duration: 0
        })
      }
      if (latest.symptoms) {
        this.$alert(`检测到症状描述：${latest.symptoms}`, '异常症状提醒', {
          confirmButtonText: '我知道了',
          callback: () => {}
        })
      }
    },
    showAbnormalDetail() {
      this.$confirm(`最近一次异常：${this.abnormalDetails}`, '异常详情', {
        confirmButtonText: '查看所有异常',
        cancelButtonText: '关闭',
        type: 'warning'
      }).then(() => {
        this.$router.push('/abnormal-records')
      })
    }
  }
}
</script>

<style scoped>
.health-container {
  padding: 20px;
}

.data-entry {
  margin-bottom: 20px;
}

.normal-range {
  font-size: 12px;
  color: #67C23A;
  margin-left: 10px;
}

.abnormal-alert {
  margin-top: 20px;
}

#healthChart {
  width: 100%;
}

.el-row {
  margin-bottom: 20px;
}

.el-col {
  padding: 0 10px;
}

@media (max-width: 768px) {
  .el-col {
    width: 100%;
    margin-bottom: 15px;
  }

  .data-entry .el-input-number {
    width: 100%;
  }

}
</style>